package com.Utils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Auther: wangyanwei
 * @Date: 2018/8/18 10:20
 * @Description:
 */
@Component
public class RedisLock {

    @Autowired
    private RedisTemplate redisTemplate;


    public boolean getLock(String key,String value){


        if(redisTemplate.opsForValue().setIfAbsent(key, value)){
            return true;
        }


        String currentValue = (String) redisTemplate.opsForValue().get(key);
        if(!StringUtils.isBlank(currentValue) && System.currentTimeMillis()>Long.parseLong(currentValue)){
            String oldValue= (String) redisTemplate.opsForValue().getAndSet(key,value);

            if(!StringUtils.isBlank(oldValue) && oldValue.equalsIgnoreCase(currentValue)){
                return true;
            }
        }

        return false;
    }


    public  void unLock(String key,String value){
        String currentValue= (String) redisTemplate.opsForValue().get(key);

        if(!StringUtils.isBlank(currentValue) && currentValue.equalsIgnoreCase(value)){
            redisTemplate.opsForValue().getOperations().delete(key);
        }

    }

}
